package com.example.taobao

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.RadioButton
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main_details.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class MainDetails : AppCompatActivity() {
    private val search = "search"
    var datas: T_shopinFo = T_shopinFo(1, "","","","","","","","","","","")

    var layoutManager : GridLayoutManager? = null
    var adapter : searchedAdapter? = null

    var dsearched_List = ArrayList<searchedData>()

    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            Log.d(search, "kkkkkkkkkkk")
            dsearched_List = msg.obj as ArrayList<searchedData>
            layoutManager = GridLayoutManager(this@MainDetails, 2)
            tuijian_card.layoutManager = layoutManager
            adapter = searchedAdapter(this@MainDetails, dsearched_List)
            tuijian_card.adapter = adapter
            adapter?.setOnItemClickListener(object: searchedAdapter.OnItemClickListener {
                override fun onItemClick(view: View, position: Int) {
                    val ins = Intent(this@MainDetails, MainDetails::class.java)

                    ins.putExtra("id", dsearched_List[position].id)
                    startActivity(ins)
                }

            })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_details)

        var Primary_ID = intent.getIntExtra("id", 1)

        initinfo(Primary_ID)
        //  init_Searched()
        initTJ()

        d_s1.setOnClickListener {
            all.scrollTo(0, d_baobei.top)
            d_s1.setTextColor(Color.BLACK)
            d_s2.setTextColor(Color.GRAY)
            d_s3.setTextColor(Color.GRAY)
        }


        d_s2.setOnClickListener {
            all.scrollTo(0, d_xq.top)
            d_s2.setTextColor(Color.BLACK)
            d_s1.setTextColor(Color.GRAY)
            d_s3.setTextColor(Color.GRAY)
        }


        d_s3.setOnClickListener {
            all.scrollTo(0, tuijian_card.top)
            d_s3.setTextColor(Color.BLACK)
            d_s2.setTextColor(Color.GRAY)
            d_s1.setTextColor(Color.GRAY)
        }

        addgwc.setOnClickListener {
            addgwc.setImageResource(R.mipmap.gwcb)
            adds(datas.id)
        }

            buyit.setOnClickListener {
            adds(datas.id)

            var bundle = Bundle()
            bundle.putDouble("total_price", datas.prices.toDouble())
            val idlist: ArrayList<Int> = ArrayList<Int>()
            val namelist: ArrayList<String> = ArrayList<String>()
            val pricelist: ArrayList<Double> = ArrayList<Double>()
            val numlist: ArrayList<Int> = ArrayList<Int>()
            val piclist: ArrayList<String> = ArrayList<String>()

            idlist.add(datas.id)
            namelist.add(datas.names)
            pricelist.add(datas.prices.toDouble())
            numlist.add(1)
            piclist.add(datas.pmain)
            var price: DoubleArray = DoubleArray(10)
            var n = pricelist.size - 1
            for (i in 0..n) {
                price[i] = pricelist[i]
            }
            bundle.putIntegerArrayList("idlist", idlist)
            bundle.putStringArrayList("namelist", namelist)
            bundle.putDoubleArray("pricelist", price)
            bundle.putIntegerArrayList("numlist", numlist)
            bundle.putStringArrayList("piclist", piclist)
            // intent.putExtras(bundle)
            //startActivityForResult(intent, 1)
            val  intent = Intent(this,buy::class.java).apply {
                putExtras(bundle)
        }

            startActivity(intent)
    }
    }

    private fun setListenter() {
        all.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            override fun onScrollChange(
                v: NestedScrollView?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if (0 < scrollY && scrollY < d_baobei.getTop()) {
                    //   setChecked(0)
                }
                else if (d_baobei.getTop() <= scrollY && scrollY < d_xq.getTop()) {
                    //  setChecked(1)
                }
                else if (d_xq.getTop() <= scrollY && scrollY < tuijian_card.getTop()) {
                    //  setChecked(2)
                }
            }})
    }

    private fun setChecked(select: Int) {
        for (i in 0 until radioGroup.childCount) {
            val radioButton = radioGroup.getChildAt(i) as RadioButton
            if(i == select)
                radioButton.setTextColor(Color.BLACK)
            else
                radioButton.setTextColor(Color.GRAY)
        }
    }


    private fun init_Searched(){
        dsearched_List.clear()
        repeat(20 ){
            dsearched_List.add(searchedData(1, " ", "美国西海岸最牛的新冠病毒套餐", "天堂太远 | 美国太近", "199", "1930"))
        }

        repeat(20 ){
            dsearched_List.add(searchedData(1, " ", "美国西海岸最牛的新冠病毒套餐", "天堂太远 | 美国太近", "400", "3"))
        }

    }

    private  fun initinfo(id:Int)
    {
        val us = "http://192.168.43.140:8080/aaa_war_exploded/insert.jsp?id=" + id
        thread {
            var url = URL(us)

            //var url = URL("https://www.baidu.com")
            val connection = url.openConnection() as HttpURLConnection
            try {
                val response = StringBuilder()
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000


                val input = connection.inputStream   //阻塞了


                val reader = BufferedReader(InputStreamReader(input) )

                reader.use {
                    reader.forEachLine {
                        if(it.length > 0)
                            response.append(it+",")
                    }
                }
                var ks  = response.split(",")
                datas = T_shopinFo(ks[0].toInt(), ks[1], ks[2], ks[3], ks[4], ks[5], ks[6], ks[7], ks[8], ks[9], ks[10], ks[11])
                showResponses(ks )
            } catch (e: Exception)
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }
    }

    private fun showResponses(datas:List<String>)
    {
        if(datas != null) {
            getImageViewInputStream(datas[1], 1)
            //Glide.with(this).load(datas[1]).into(d_mainImage)
            d_price.text = datas[2]
            d_xiaoliang.text = datas[6]
            d_shopInfo.text = datas[5]
            d_xiaoliang.text = "月销" + datas[4]
            d_chanping.text = datas[3]

            /*  Glide.with(this).load(datas[7]).into(holder.shopImage)
              Glide.with(this).load(shop.src).into(holder.shopImage)
              Glide.with(this).load(shop.src).into(holder.shopImage)
              Glide.with(this).load(shop.src).into(holder.shopImage)
              Glide.with(this).load(shop.src).into(holder.shopImage)*/
            getImageViewInputStream(datas[7], 2)
            getImageViewInputStream(datas[8], 3)
            getImageViewInputStream(datas[9], 4)
            getImageViewInputStream(datas[10], 5)
            getImageViewInputStream(datas[11], 6)
        }
    }



    fun getImageViewInputStream(urls : String,  i :Int) {
        thread {


            if(i == 1)
                showResponse1(urls)
            else if( i == 2)
                showResponse2(urls)
            else if( i == 3)
                showResponse3(urls)
            else if( i == 4)
                showResponse4(urls)
            else if( i == 5)
                showResponse5(urls)
            else if( i == 6)
                showResponse6(urls)
        }
    }

    private  fun showResponse1(ins: String) {
        runOnUiThread {
            Glide.with(this).load(ins).into(d_mainImage)
        }
    }
    private  fun showResponse2(ins: String)
    {
        runOnUiThread{
            Glide.with(this).load(ins).into(d_p1)
        }

    }
    private  fun showResponse3(ins: String)
    {
        runOnUiThread{
            Glide.with(this).load(ins).into(d_p2)
        }
    }
    private  fun showResponse4(ins: String)
    {
        runOnUiThread{
            Glide.with(this).load(ins).into(d_p3)
        }
    }
    private  fun showResponse5(ins: String)
    {
        runOnUiThread{
            Glide.with(this).load(ins).into(d_p4)
        }
    }
    private  fun showResponse6(ins: String)
    {
        runOnUiThread{
            Glide.with(this).load(ins).into(d_p5)
        }
    }


    private fun initTJ()
    {
        val us = "http://192.168.43.140:8080/aaa_war_exploded/randomB.jsp"
        thread {
            var url = URL(us)
            //var url = URL("https://www.baidu.com")
            val connection = url.openConnection() as HttpURLConnection
            try {
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                connection.requestMethod = "POST"

                connection.setRequestProperty("Accept-Charset", "UTF-8" )
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input) )

                var src : String = ""
                var id : Int = 0
                var names:String = ""
                var describe:String = ""
                var prices:String = ""
                var sales:String= ""
                var i = 0

                var meg : ArrayList<searchedData> = ArrayList<searchedData>()

                reader.use {
                    reader.forEachLine {
                        if(it.length > 0) {
                            if( i == 0)
                                id = it.toInt()
                            else if( i == 1)
                                src = it
                            else if ( i == 2)
                                names = it
                            else if( i == 3)
                                describe = it
                            else if(i  == 4)
                                prices = it
                            else if( i == 5)
                            {
                                sales = it
                                i = -1
                                meg.add(searchedData(id, src, names, describe, prices , sales))
                            }
                            i++
                        }
                    }
                }

                dsearched_List = meg
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)


                //  showResponse(response.toString() )
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }

    }

    private fun adds(id: Int)
    {
        thread {
            var url = URL("http://192.168.43.140:8080/aaa_war_exploded/addShopCart.jsp?id="+id)
            val connection = url.openConnection() as HttpURLConnection
            try {
                connection.requestMethod = "POST"
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                // val reader = BufferedReader(InputStreamReader(input))
                /* reader.use {
                     reader.forEachLine {

                     }
                 }*/
            } catch (e: Exception )
            {
                e.printStackTrace();
            } finally {
                connection.disconnect()
            }
        }
    }
}